//用户的城市信息
import {
  defineStore
} from 'pinia';
import {
  reactive
} from 'vue'
import * as http from '@/utils/http'

export const uselocation = defineStore('location', () => {

  const locationInfo = reactive({
    "longitude ": null,
    "latitude ": null,
    "name": null,
    "id": null
  });
  async function getLocationInfo() {
    uni.getLocation({
      type: 'wgs84',
      success: async (res) => {
        console.log('当前位置的经度：' + res.longitude);
        console.log('当前位置的纬度：' + res.latitude);
        // 调用后端接口根据得到的经纬度获取地址
        let param = {
          longitude: res.longitude,
          latitude: res.latitude
        }
        const cityResult = await http.getRequest("/peizhen/open-city/location", param)
        // console.log(cityResult);
        if (cityResult.code == 0) {
          setLocation(cityResult.data.id, cityResult.data.name)
        } else {
          //由于异常没获取到城市地址默认为郑州
          setLocation('410100', '郑州市')
        }
      },
      // 若用户点击拒绝获取位置则弹出提示
      fail: (err) => {
        uni.showModal({
          content: '检测到您没打开获取位置功能权限，是否去设置打开？',
          confirmText: "确认",
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (res) => {
                  uni.showToast({
                    title: '授权后请重新打开此页面',
                    icon: 'none'
                  })
                },
                fail: (err) => {
                  console.log(err)
                }
              })
            } else {
              uni.showToast({
                title: '获取地理位置授权失败',
                icon: 'none',
                success: () => {
                  // 返回上一页
                  setTimeout(() => {
                    uni.showToast({
                      title: "返回上一页",
                      icon: 'none'
                    })
                    // uni.navigateBack({
                    //   delta: 1
                    // })
                  }, 500)
                }
              })
            }
          }
        })
      },
    })
  }

  function setLocation(id, name) {
    locationInfo.id = id
    locationInfo.name = name
    //将城市信息存储到本地缓存
    uni.setStorageSync("location", {
      id: locationInfo.id,
      name: locationInfo.name
    })
  }
  return {
    locationInfo,
    getLocationInfo,
    setLocation
  };
});